# -*- coding: UTF-8 -*-
"""常用工具类"""
from datetime import datetime, timedelta


# 将采购时间转换为批次编号(delta为0时，时间应为iso时间)，delta为正则加为负则减
def time_to_batch_no(dt, delta_hour=0, delta_day=0, err=''):
    try:
        if dt and isinstance(dt, datetime):
            if delta_hour or delta_day:
                time_delta = timedelta(hours=int(delta_hour), days=int(delta_day))
                dt = dt + time_delta
            return int(dt.strftime("%Y%m%d"))
    except ValueError:
        return err


# 将批次编号转时间
def batch_no_to_gen_time(batch_no, err=''):
    try:
        if batch_no:
            # UTC时间相当于中国18:00
            batch_no = str(batch_no) + '100000'
            return datetime.strptime(batch_no, "%Y%m%d%H%M%S")
    except ValueError:
        return err


# 将批次编号转年
def batch_to_year(batch_no, err=''):
    try:
        if batch_no:
            return str(batch_no)[:4]
    except ValueError:
        return err


# 测试
if __name__ == '__main__':
    # dt = '2018-11-30 20:40:30'
    # ts = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
    # print(ts)
    # print(batch_no_to_gen_time('20181130'))

    # client = MongoClient('mongodb://root:Dangerous!@zc-outer.mongodb.rds.aliyuncs.com:3717')
    # test = client['cmcc_test']
    # prod = client['cmcc_2019']
    #
    # orders = test['t_order'].find()
    # prod['t_order'].insert_many(orders)
    # 今天的n天后的日期。
    # now = datetime.now()
    # delta = timedelta(days=1)
    # n_days = now - delta
    # print(n_days.strftime('%Y-%m-%d %H:%M:%S'))

    print(time_to_batch_no(datetime.now()))
    print(time_to_batch_no(datetime.now(), delta_day=-2))
    print(time_to_batch_no(datetime.now(), delta_hour=-14))
